<!--
 * @description  : 市管-日计划制定
 * @descriptionDetail: 市管-日计划制定
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-09 18:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->
    <u-toast ref="uToast" />
    <u-form :model="planForm" :rules="rules" :errorType="errorType" style="padding: 0px 15px;" ref="uForm">
      <u-form-item left-icon="calendar" required label="检查日期" prop="planDate" :label-width="180" right-icon="arrow-right">
        <u-input input-align="right" :custom-style="valueStyle" placeholder="请选择检查日期" :disabled="true" v-model="planForm.planDate" @tap="!isDisabled && (dateShow=true)" />
      </u-form-item>
      <u-form-item left-icon="list-dot" required label="计划类型" prop="dayPlanTypeName" :label-width="180" right-icon="arrow-right">
        <u-input input-align="right" :needValid="true" :custom-style="valueStyle" placeholder="请选择计划类型" :disabled="true" v-model="planForm.dayPlanTypeName" @tap="!isDisabled && (planTypeShow = true)" />
      </u-form-item>
      <u-form-item left-icon="man-add" required label="执行人" prop="checkers" :label-width="180" right-icon="arrow-right">
        <u-input style="flex: 1;" :needValid="true" input-align="right" :custom-style="valueStyle" placeholder="请选择执行人" :disabled="true" v-model="planForm.checkers" @tap="!isDisabled && planForm.dayPlanType =='01' && (personShow=true)" />
      </u-form-item>
      <u-form-item left-icon="account" label="制定人" :label-width="180">
        <u-input input-align="right" :custom-style="valueStyle" :disabled="true" v-model="planForm.userName" />
      </u-form-item>
    </u-form>
    <view class="divider-info">
      检查客户<u-tag class="client-num" type="primary" :text="clients.length" shape="circle" />
      <span class="sub-info" v-if="!isDisabled">(向左滑动删除)</span>
      <u-icon style="float:right;" :color="$theme.u_type_primary" name="plus" size="38" v-if="!isDisabled" @click="handlerDoMore()"></u-icon>
    </view>
    <view class="card" v-for="(item, index) in clients" :key="item.id">
      <u-swipe-action
        :index="index"
        :show="item.show"
        :options="options"
        :disabled="isDisabled"
        @click="handlerDeleteClient(item)"
        @open="handlerOpen(index)"
      >
        <client-item :client="item"></client-item>
      </u-swipe-action>
    </view>
    <view class="space-content"></view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="!isDisabled">
      <u-button plain class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit(M_DAY_PLAN_STATUS.DRAFT)">
        保存计划
      </u-button>
      <u-button class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit(M_DAY_PLAN_STATUS.SUBMITTED)">
        提交计划
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 检查日期 -->
    <u-calendar :min-date="getMinDate()" :mode="mode" max-date="9999-12-31" v-model="dateShow" @change="calendarChange"></u-calendar>
    <!-- 计划类型 -->
    <u-select :list="planTypeDict" v-model="planTypeShow" @confirm="hanlderChangePlanType"></u-select>
    <!-- 执行人 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="personShow">
      <multi-select :leftBtnOpt="leftBtnOpt" :options="personOptions" @select="handlerSelectPersons"></multi-select>
    </u-popup>
    <!-- 执行人选择更多 -->
    <u-popup mode="bottom" height="80%" v-model="orgPersonSelectShow">
      <org-person-select treeType="zm-user" modelType="market" @choose="handlerChoosePerson"></org-person-select>
    </u-popup>
    <!-- 添加零售户 -->
    <u-popup mode="bottom" height="100%" v-model="retailerShow">
      <retailer-list></retailer-list>
    </u-popup>
    <!-- 添加操作按钮 -->
    <u-action-sheet :list="addBtnsList" v-model="isOpen" @click="handlerDropMenu"></u-action-sheet>
  </view>
</template>
<script>
import multiSelect from '@/components/multi-select.vue';
import checkService from "@/service/check/check.service"
import commonService from "@/service/common/common.service";
import ClientItem from './components/client-item.vue';
import RetailerList from './retailerList.vue';
import OrgPersonSelect from "@/components/org-person-select.vue";
import {LOG_STATUS,LOG_OP_TYPE,} from '@/service/common/mapping/enum.js';
import {M_DAY_PLAN_STATUS,} from "@/service/check/mapping/enum.js";
export default {
  components: { multiSelect, ClientItem, RetailerList,OrgPersonSelect, },
  data() {
    return {
      M_DAY_PLAN_STATUS,
      isOpen: false,
      dateShow: false,  // 日期选择
      checkDate: "",    // 检查日期
      iflow: '0', // 是否走审批开关 0关闭 1打开
      nextPersonUuids: [],
      nowDay: this.$u.date(Date.now(),'yyyy-mm-dd'),
      mode: "date",
      valueStyle: {
        marginRight: "5px",
      },
      errorType: ["border-bottom","message",],
      planForm: {
        planDate: '',
        dayPlanType: '01',
        dayPlanTypeName: '重点检查',
        actionName:'',
        actionUuid:'',
      },
      rules: {
        planDate: [
          {
            required: true,
            message: '请选择检查日期',
            trigger: ['change','blur',],
          },
        ],
        dayPlanTypeName: [
          {
            required: true,
            message: '请选择计划类型',
            trigger: ['change','blur',],
          },
        ],
        checkers: [
          {
            message: '请选择执行人',
            trigger: ['change','blur',],
            validator: (rule, value, callback) => {
              if (this.planTypeId == '02') {  // 随机检查时校验
                if (this.planTypeStatus) {  //  true为必填
                  if (!this.$u.test.isEmpty(value)) {
                    return true
                  } else {
                    return false;
                  }
                } else {
                  return true
                }
              } else {  // 重点检查时校验
                if(!this.$u.test.isEmpty(value)){
                  return true;
                } else {
                  return false;
                }
              }
            },
          },
        ],
      },
      planTypeShow: false,
      planTypeDict: [
        { value: '01', label: '重点检查', },
        { value: '02', label: '随机检查', },
      ],
      taskSourceMap: {'3': '10', '4': '11',},
      personShow: false,
      orgPersonSelectShow:false,
      personOptions: [],
      selectPersons: [],
      newTaskList: [],
      retailerShow: false,  // 零售户选择
      clients: [],  // 选中的检查户
      delClientTaskPoolList:[], // 删除的记录
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#dd524d',
          },
        },
      ],
      leftBtnOpt:{
        isBack:true,
        backText:"更多选择",
        backIconName:"man-add",
        backFun:() => {},
      },
      addBtnsList: [],  // 添加操作按钮
      submitBtnLoading: false,  // 提交按钮显示加载
      plan: this.getRouteParam() || {}, // 计划数据
      isDisabled: false,
      beginTime: "",
      planTypeId: "",
      planTypeStatus:false, // 判断随机检查，保存时必填，其余状态非必填
    }
  },
  onShow() {

  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  mounted() {
    this.leftBtnOpt.backFun = (pItems) => {
      this.personShow = false;
      this.selectPersons = pItems;
      this.orgPersonSelectShow = true;
    };
  },
  created() {
    this.initPlan();
    this.getPlanApproveSwitch(); // 获取开关详情 bln 11.16
  },
  methods: {
    initPlan() {
      // 调用详情接口
      if(this.plan.dayUuid){
        this.queryPlanData();
      }else{
        // 新制定计划
        this.planForm = Object.assign({}, this.plan);
        !this.planForm.userName && (this.planForm.userName = this.curUser.user.personName);
        !this.planForm.planDate && (this.planForm.planDate = this.nowDay);
        !this.planForm.dayPlanType && (this.planForm.dayPlanType = '01');
        !this.planForm.dayPlanTypeName && (this.planForm.dayPlanTypeName = '重点检查');
        this.isDisabled = this.plan.dayUuid && this.plan.status != M_DAY_PLAN_STATUS.DRAFT;
      }
      this.planExecutorList();
    },
    planExecutorList(){
      // 查询执行人
      this.$u.loading("加载中...");
      checkService.findDayPlanExecutorList({planDate:this.planForm.planDate,dayPlanType:this.planForm.dayPlanType,}).then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          let ps = dr.data;
          ps.map(p => {
            p.uid = p.personUuid;
            p.name = p.personName;
            p.exts = [p.inspectionCertNo, p.mainJobName,];
          });
          this.$nextTick(() => this.personOptions = ps);
        }
      }).catch((err) => {
        this.$u.toast(err);
        this.$u.hideLoading();
      });
    },
    // 选择执行人
    handlerChoosePerson(psrList){
      this.orgPersonSelectShow = false;
      psrList = psrList.filter(itm => {
        for (let i = 0; i < this.selectPersons.length; i++) {
          if(this.selectPersons[i].personUuid == itm.id){
            return false;
          }
        }
        return true;
      });
      let newList = psrList.map((item) => {
        return {
          personUuid:item.id,
          personName:item.name,
        }
      });
      this.selectPersons = [...this.selectPersons,...newList,];
      let pNames = [];
      this.selectPersons.forEach(p => {
        pNames.push(p.personName);
      });
      if(pNames.length <= 1){
        this.$u.toast('至少选择两个执行人');
        return;
      }
      this.planForm.checkers = pNames.join(",");
    },
    getMinDate(){
      return this.$u.timeFormat(Date.now());
    },
    planTypeClick(){
      this.planTypeShow = true;
    },
    // 日历选择时调用
    calendarChange(d){
      this.planForm.planDate = d.result;
      // 选择日期后清空执行人数据，重新调用执行人接口
			if(this.planForm.dayPlanType == '01') {
				this.planForm.checkers = '';
				this.selectPersons = [];
				this.planExecutorList();
			}
    },
    // 根据页面返回的参数处理相应逻辑
    updateBackState(param){
      let list = [];
      let executorList = [];
      // 添加重点监管户任务
      if(param['keySupervisionTask']){
        list = param['keySupervisionTask'];
      } else if(param['temporaryTask']){
        // 添加临时任务
        list = param['temporaryTask'];
      }else if(param['randomTask']){
        // 添加随机任务
        list = param['randomTask'].list;
        executorList = param['randomTask'].executorList;
        this.planForm.checkers = param['randomTask'].checkers;
      }else if(param['keySupervisionTaskMap']){
        // 重点监管户任务地图选择
        list = param['keySupervisionTaskMap'];
      } else if (param.flowUserSelectBack) {
        // 选择审批人
        for (let fu of param.flowUserSelectBack) {
          this.nextPersonUuids.push(fu.personId);
        }
        if (this.nextPersonUuids.length === 0) {
          this.$u.toast('请选择审批人');
          return
        } else {
          this.submit(M_DAY_PLAN_STATUS.SUBMITTED)
        }
      }
      list.forEach(c => {
        if (this.clients.filter(r => r.retailerUuid == c.retailerUuid).length > 0) {
          this.$u.toast(`【${c.companyName}】已存在`);
        } else {
          this.clients.push(c);
        }
      });

      let newList = [...this.selectPersons, ...executorList,];
      let obj = {};
      let result = newList.reduce((item,next) => {
        obj[next.personUuid] ? '' : obj[next.personUuid] = true && item.push(next)
        return item
      },[]);
      this.selectPersons = newList;
      console.log(result);

    },
    // 查询计划详情
    queryPlanData() {
      this.$u.loading("加载中...");
      checkService.getDayPlan(this.plan.dayUuid).then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          this.planForm = dr.bean;
          this.planForm.userName = this.plan.userName;
          this.selectPersons = dr.bean.executorList;
          this.clients = dr.bean.taskPoolQueryVOS;
          this.isDisabled = this.planForm.dayUuid && this.planForm.status != M_DAY_PLAN_STATUS.DRAFT;
          this.planTypeId = dr.bean.dayPlanType
        }
      }).catch((er) => {
        this.$u.hideLoading();
        this.$u.toast(er);
      });
    },
    // 选择计划类型
    hanlderChangePlanType(p) {
      // 切换计划类型提示清空已选检查客户
      this.planTypeId = p[0].value;
      if (this.clients.length > 0 && this.planForm.dayPlanType != p[0].value) {
        this.$modal.confirm("确认清空已选的检查客户吗？", () => {
          this.planForm.dayPlanType = p[0].value;
          this.planForm.dayPlanTypeName = p[0].label;
          this.clients = [];
          this.planForm.checkers = '';
          this.selectPersons = [];
        });
      } else {
        this.planForm.dayPlanType = p[0].value;
        this.planForm.dayPlanTypeName = p[0].label;
        this.planForm.checkers = '';
        this.selectPersons = [];
      }
    },
    // 执行人
    handlerSelectPersons(pItems) {
      this.personShow = false;
      if((pItems || []).length <= 1){
        this.$u.toast('至少选择两个执行人');
        return;
      }
      this.selectPersons = pItems;
      let pNames = [];
      this.selectPersons.forEach(p => {
        pNames.push(p.name);
      });
      this.planForm.checkers = pNames.join(",");
    },
    // 删除选中的客户
    handlerDeleteClient(cItem) {
      this.clients = this.clients.filter(c => c.retailerUuid != cItem.retailerUuid);
      if(cItem.taskPools){
        cItem.taskPools.forEach(ipt => {
          !this.delClientTaskPoolList.includes(ipt.taskUuid) && this.delClientTaskPoolList.push(ipt.taskUuid);
        });
      }
    },
    handlerOpen(idx) {
      this.clients.map((c, i) => {
        c.show = i == idx;
      });
      this.$forceUpdate();
    },
    // 检查显示更多
    handlerDoMore() {
      if(this.$u.test.isEmpty(this.planForm.dayPlanType)){
        this.$u.toast('请选择计划类型');
        return;
      }
      this.addBtnsList = this.planForm.dayPlanType == '01' ? [
        {text: "添加任务池任务",} ,
        {text: "任务池任务地图选择",} ,
        {text: "添加临时任务",},
        {text: "添加临时任务地图选择",},
      ] : [{text: "添加随机抽取任务",},];
      this.isOpen = true;
    },
    // 导航栏菜单
    handlerDropMenu(i) {
      this.isOpen = false;
      if (!this.planForm.planDate) {
        this.$modal.alert("请先选择检查日期");
        return;
      }
      switch(i) {
      case 0:
        this.setRouteParam(this.clients);
        // 添加重点监管任务
        if(this.planForm.dayPlanType == '01'){
          this.$u.route('/pages/check/keySupervisionTask?taskType=' + this.planForm.dayPlanType
			+ '&checkDate=' + this.planForm.planDate);
          break;
        }else{
          // 添加双随机任务
          this.$u.route('/pages/check/randomTask?checkDate=' + this.planForm.planDate);
          break;
        }
      case 1:
        // 重点监管任务地图选择
        this.$u.route('/pages/check/keySupervisionTaskMap?taskType=' + this.planForm.dayPlanType); // ?taskType=' + this.planForm.dayPlanType + '&checkDate=' + this.planForm.planDate
        break;
      case 2:
        // 添加临时任务
        this.$u.route('/pages/check/temporaryTask?isDayPlan=true');
        break;
      case 3:
        // 添加临时任务地图
        this.$u.route('/pages/check/temporaryTaskMap');
        break;
      default:
        break;
      }
    },
    toSelectPerson(){
      this.$u.route({
      url: "/pages/commonPage/flowUserSelectComponent",
      params: {
        flowFormCode: "dayPlanApproval", // 日计划审批的gfcode
      },
      });
    },
    // 判断审批开关 bln 11.13
    getPlanApproveSwitch () {
      commonService.getSysConfigList({
        limit:15,
        page:1,
        configKey : 'market_archive_config',
        configSubKey : 'dayplan_isapprove'
      }).then(res => {
        if (res.success) {
          this.iflow = res.data[0].configValue;
        } else {
          this.$u.toast(res.msg);
        }
      }).catch((err) => {
        this.$u.toast(err);
      });
    },
    submit (status) {
      let planData = {
        status: status,
        planDate: this.planForm.planDate,
        dayPlanType: this.planForm.dayPlanType,
        dayUuid: this.plan.dayUuid || "",
        taskList : this.newTaskList,
        executorVOList:this.selectPersons,
        delTaskUuids: this.delClientTaskPoolList.join(',')
      };
      let service = "";
      if (status == M_DAY_PLAN_STATUS.SUBMITTED && this.iflow == '1' && this.planForm.dayPlanType == '01') {
        planData.status = M_DAY_PLAN_STATUS.APPROVEING
        planData.nextPersonUuids = this.nextPersonUuids.join(',')
        service = checkService.submitDayPlan(planData)
      } else {
        service = checkService.newSaveDayPlan(planData)
      }
      service.then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          this.backPrev({
            paramKey: "refresh",
            param : true,
          });
        } else {
          this.$u.toast(dr.msg);
          this.planTypeStatus = false;
        }
      }).catch((err) => {
        this.$u.hideLoading();
        this.$u.toast(err);
      });
    },
    // 保存或提交
    handlerDoSubmit (status) {
      this.planTypeStatus = true;
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.clients.length == 0) {
            this.$u.toast("请选择检查客户");
            this.planTypeStatus = false;
            return;
          }
					if(this.selectPersons.length == 0) {
						this.$u.toast("请选择执行人");
						this.planTypeStatus = false;
						return;
					}
					// 修复 日计划保存后 再次提交只有一条数据的bug fsx 2023-12-28 开始
          let newTaskList = []
          this.clients.forEach((item) => {
            if(item.taskPools){
              newTaskList = [...newTaskList,...item.taskPools];
            }else{
             newTaskList.push(item);
            }
          });
					// 修复 日计划保存后 再次提交只有一条数据的bug fsx 2023-12-28 结束
          this.$modal.confirm(`确定${status == M_DAY_PLAN_STATUS.SUBMITTED ? '提交' : '保存'}吗？`, () => {
            this.$u.loading(`${status == M_DAY_PLAN_STATUS.SUBMITTED ? '提交' : '保存'}中...`);
            let checkPersons = [];
            let checkersLicNos = [];
            if (this.selectPersons.length > 0) {
              this.selectPersons.forEach(p => {
                checkPersons.push(p.personUuid || p.id);
                checkersLicNos.push(p.certNo);
              });
            } else {
              checkPersons = this.plan.checkers.split(",");
              checkersLicNos = this.plan.checkersLicNo.split(",");
            }
            let planData = {
              planDate: this.planForm.planDate,
              dayPlanType: this.planForm.dayPlanType,
              status: status,
              dayUuid: this.plan.dayUuid || "",
              taskList : newTaskList,
              delTaskUuids: this.delClientTaskPoolList.join(','),
              executorVOList:this.selectPersons,
            };
            checkService.newSaveDayPlan(planData).then(dr => {
              this.$u.hideLoading();
              if (dr.success) {
                this.backPrev({
                  paramKey: "refresh",
                  param : true,
                });
              } else {
                this.$u.toast(dr.msg);
                this.planTypeStatus = false;
              }
            }).catch((err) => {
              this.$u.hideLoading();
              this.$u.toast(err);
            });
          }, () => {
            this.planTypeStatus = false;
          },);
        } else {
          this.planTypeStatus = false;
          console.error('验证失败');
        }
      });
    },
  },
}
</script>
<style lang="scss" scoped>
.page{padding: 0;}
.divider-info {
  font-size: 16px;
  margin: 5px 15px 10px 15px;
  color: #333;
  font-weight: 600;
  .sub-info {
    font-weight: 100;
    font-size: 14px;
    color: #000;
  }
}
.page {
  padding-bottom: 55px;
}
.client-num {
  padding: 3px 5px;
  font-weight: bold;
  margin: 0px 5px;
  font-size: 14px;
}
.bottom-btns {
  position: fixed;
  bottom: 0px;
  width: 100%;
  background-color: #f8f8f8;
  //padding: 5px 0px;
}
// h5端部分浏览器input设置disabled后点击事件失效 2023-10-24 fsx start
	/deep/.uni-input-input {
		pointer-events: none !important;
	}
	// h5端部分浏览器input设置disabled后点击事件失效 2023-10-24 fsx end
</style>
